import json
from backend.app.app.db.session_project import session_pro
import backend.app.app.models.db_owi_private_models as md_pro
import backend.app.app.models.db_owi_public_models as md_pub
from sqlalchemy import desc
from backend.app.app.db.session_public import session_pub


def get_proId_by_user_id(user_id):
    try:
        project_inf = session_pro.query(md_pro.TbUserprojDvpunitOilstimevalInput.Proj_ID) \
            .filter(md_pro.TbUserprojDvpunitOilstimevalInput.User_ID == user_id
                    ) \
            .order_by(desc(md_pro.TbUserprojDvpunitOilstimevalInput.Proj_ID)).all()

        return project_inf
    except:
        print('查找数据失败')
        session_pro.rollback()
        return False


#   根据user_id,pro_id获取名字，类型，年度
def get_name(user_id, pro_id):
    try:
        project_inf = session_pro.query(md_pro.TbUserprojDvpunitOilstimevalInput).filter(
            md_pro.TbUserprojDvpunitOilstimevalInput.User_ID == user_id,
            md_pro.TbUserprojDvpunitOilstimevalInput.Proj_ID == pro_id
            ).all()
        result = [data.__dict__ for data in project_inf]
        return result
    except:
        print('输入数据查找数据失败')
        session_pro.rollback()
        return False


# 根据单元名称获取所有输入界面信息,开发单元，类别名称，年份
def get_query_data_by_id(user_id, pro_id):
    try:
        project_inf = session_pro.query(md_pro.TbUserprojDvpunitOilstimevalInput).filter(
            md_pro.TbUserprojDvpunitOilstimevalInput.User_ID == user_id,
            md_pro.TbUserprojDvpunitOilstimevalInput.Proj_ID == pro_id
            ).all()
        result = [data.__dict__ for data in project_inf]
        return result
    except:
        print('输入数据查找数据失败')
        session_pro.rollback()
        return False


# 根据单元名称获取所有输入界面信息,开发单元，类别名称，年份 hzc改
def get_query_data(dvpUnit_Name, stim_type, plan, year):
    if not dvpUnit_Name and stim_type and year:
        print("数据有误")
        return False
    return_data = dict()
    dvp_unit_name = dvpUnit_Name[0]
    stim_type = stim_type[0]
    return_data.update(
        {
            'DvpUnit_Name': dvp_unit_name,
            'StimType_Name': stim_type,
            'Year': year,
            'DvpUnit_OilStim_PlanProj_Name': plan
        }
    )
    # 获取有效井次、有效率、有效期、措施增油量、预测方法
    try:
        data_one = session_pub.query(
            md_pub.TbYearDvpunitOilstimPlanprojForecast.Forecast_Method,
            md_pub.TbYearDvpunitOilstimPlanprojForecast.Stim_WellValidRatio,
            md_pub.TbYearDvpunitOilstimPlanprojForecast.Stim_WellNumber_Valid,
            md_pub.TbYearDvpunitOilstimPlanprojForecast.Stim_ValidPeriod_Average,
            md_pub.TbYearDvpunitOilstimPlanprojForecast.Stim_IncreOil_Average
        ).filter(
            md_pub.TbYearDvpunitOilstimPlanprojForecast.DvpUnit_Name == dvpUnit_Name,
            md_pub.TbYearDvpunitOilstimPlanprojForecast.StimType_Name == stim_type,
            md_pub.TbYearDvpunitOilstimPlanprojForecast.DvpUnit_OilStim_PlanProj_Name == plan,
            md_pub.TbYearDvpunitOilstimPlanprojForecast.Year == year
        ).first()

        return_data.update(dict(zip(data_one.keys(), data_one) if data_one else {
            'Forecast_Method': None,
            'Stim_WellValidRatio': None,
            'Stim_WellNumber_Valid': None,
            'Stim_ValidPeriod_Average': None,
            'Stim_IncreOil_Average': None
        }))
        print(return_data)
    except Exception as e:
        print(e)
        print(e.__traceback__.tb_lineno)
        return False

    # 获取预测作业费用
    try:
        stim_cost = session_pub.query(
            md_pub.TbYearDvpunitPlanprojOilstimCost.Stim_Cost
        ).filter(
            md_pub.TbYearDvpunitPlanprojOilstimCost.DvpUnit_Name == dvp_unit_name,
            md_pub.TbYearDvpunitPlanprojOilstimCost.Year == year,
            md_pub.TbYearDvpunitPlanprojOilstimCost.StimType_Name == stim_type,
            md_pub.TbYearDvpunitPlanprojOilstimCost.DvpUnit_OilStim_PlanProj_Name == plan

        ).first()
        return_data.update({'Stim_Cost': stim_cost[0] if stim_cost else None})
    except Exception as e:
        print(e)
        print(e.__traceback__.tb_lineno)
        return False

    # 获取原油商品率，原油价格
    try:
        data_two = session_pub.query(
            md_pub.TbYearDvpunitPlanprojOilprice.Oil_CommodityRatio,
            md_pub.TbYearDvpunitPlanprojOilprice.Oil_Price
        ).filter(
            md_pub.TbYearDvpunitPlanprojOilprice.DvpUnit_Name == dvp_unit_name,
            md_pub.TbYearDvpunitPlanprojOilprice.Year == year
        ).first()
        return_data.update(
            dict(zip(data_two.keys(), data_two)) if data_two else {'Oil_CommodityRatio': None, 'Oil_Price': None})
    except Exception as e:
        print(e)
        print(e.__traceback__.tb_lineno)
        return False

    # 获取操作吨油成本
    try:
        oil_opr_cost = session_pub.query(
            md_pub.TbYearDvpunitPlanprojOilprodcost.Oil_OprCost
        ).filter(
            md_pub.TbYearDvpunitPlanprojOilprodcost.Year == year,
            md_pub.TbYearDvpunitPlanprojOilprodcost.DvpUnit_OilStim_PlanProj_Name == plan,
            md_pub.TbYearDvpunitPlanprojOilprodcost.DvpUnit_Name == dvp_unit_name
        ).first()
        return_data.update({'Oil_OprCost': oil_opr_cost[0] if oil_opr_cost else None})
    except Exception as e:
        print(e)
        print(e.__traceback__.tb_lineno)
        return False

    # 销售税费率
    try:
        oil_sale_total_tax_ratio = session_pub.query(
            md_pub.TbYearDvpunitPlanprojOilsalecostRatio.OilSale_TotalTaxRatio
        ).filter(
            md_pub.TbYearDvpunitPlanprojOilsalecostRatio.Year == year,
            md_pub.TbYearDvpunitPlanprojOilsalecostRatio.DvpUnit_OilStim_PlanProj_Name == plan,
            md_pub.TbYearDvpunitPlanprojOilsalecostRatio.DvpUnit_Name == dvp_unit_name
        ).first()
        return_data.update({'OilSale_TotalTaxRatio': oil_sale_total_tax_ratio[0] if oil_sale_total_tax_ratio else None})
    except Exception as e:
        print(e)
        print(e.__traceback__.tb_lineno)
        return False

    # 获取资金贴现率
    try:
        money_discount = session_pub.query(
            md_pub.TbYearDvpunitPlanprojDiscount.Money_Discount
        ).filter(
            md_pub.TbYearDvpunitPlanprojDiscount.DvpUnit_Name == dvp_unit_name,
            md_pub.TbYearDvpunitPlanprojDiscount.DvpUnit_OilStimulate_PlanProj_Name == plan,
            md_pub.TbYearDvpunitPlanprojDiscount.Year == year
        ).first()
        return_data.update({'Money_Discount': money_discount[0] if money_discount else None})
    except Exception as e:
        print(e)
        print(e.__traceback__.tb_lineno)
        return False

    return return_data

# def get_query_data(dvpUnit_Name, stimType_Name, plan, year):
#     project_inf = dict()
#     dvpUnit_Name = dvpUnit_Name[0]
#     stimType_Name = stimType_Name[0]
#     if dvpUnit_Name and stimType_Name and year:
#         project_inf['DvpUnit_Name'] = dvpUnit_Name
#         project_inf['StimType_Name'] = stimType_Name
#         project_inf['plan'] = plan
#         project_inf['Year'] = year
#     try:
#         stim_cost = session_pub.query(
#             md_pub.TbYearDvpunitOilstimCost.Stim_Cost  # 作业费用
#         ).filter(
#             md_pub.TbYearDvpunitOilstimCost.DvpUnit_Name == dvpUnit_Name,
#             md_pub.TbYearDvpunitOilstimCost.StimType_Name == stimType_Name,
#             md_pub.TbYearDvpunitOilstimCost.Year == year
#         ).first()
#         project_inf['Stim_Cost'] = None
#         if stim_cost:
#             project_inf.update({'Stim_Cost': stim_cost[0]})
#
#         price = session_pub.query(
#             md_pub.TbYearDvpunitOilprice.Oil_CommodityRatio,  # 原油商品率
#             md_pub.TbYearDvpunitOilprice.Oil_Price  # 原油价格
#         ).filter(
#             md_pub.TbYearDvpunitOilprice.DvpUnit_Name == dvpUnit_Name,
#             md_pub.TbYearDvpunitOilprice.Year == year
#         ).first()
#         project_inf['Oil_CommodityRatio'] = None
#         project_inf['Oil_Price'] = None
#         if price:
#             data = dict(zip(price.keys(), price))
#             project_inf.update(
#                 {'Oil_CommodityRatio': data['Oil_CommodityRatio']})
#             project_inf.update({'Oil_Price': data['Oil_Price']})
#
#         prod_cost = session_pub.query(
#             md_pub.TbYearDvpunitOilprodcost.Oil_OprCost  # 操作吨油成本
#         ).filter(
#             md_pub.TbYearDvpunitOilprodcost.DvpUnit_Name == dvpUnit_Name,
#             md_pub.TbYearDvpunitOilprodcost.Year == year
#         ).first()
#         project_inf['Oil_OprCost'] = None
#         if prod_cost:
#             project_inf.update({'Oil_OprCost': prod_cost[0]})
#
#         sale_cost_ratio = session_pub.query(
#             md_pub.TbYearDvpunitOilsalecostRatio.OilSale_TotalTaxRatio  # 销售税费率
#         ).filter(
#             md_pub.TbYearDvpunitOilsalecostRatio.DvpUnit_Name == dvpUnit_Name,
#             md_pub.TbYearDvpunitOilsalecostRatio.Year == year
#         ).first()
#         project_inf['OilSale_TotalTaxRatio'] = None
#         if sale_cost_ratio:
#             project_inf.update({'OilSale_TotalTaxRatio': sale_cost_ratio[0]})
#
#         discount = session_pub.query(
#             md_pub.TbYearDvpunitDiscount.Money_Discount  # 资金贴现率
#         ).filter(
#             md_pub.TbYearDvpunitDiscount.DvpUnit_Name == dvpUnit_Name,
#             md_pub.TbYearDvpunitDiscount.Year == year
#         ).first()
#         project_inf['Money_Discount'] = None
#         if discount:
#             project_inf['Money_Discount'] = discount[0]
#
#         plan_proj = session_pub.query(
#             md_pub.TbYearDvpunitOilstimResult.Stim_WellValidRatio,  # 有效率
#             md_pub.TbYearDvpunitOilstimResult.Stim_WellNumber_Valid,  # 有效井次
#             md_pub.TbYearDvpunitOilstimResult.Stim_ValidPeriod_Average,  # 平均有效期
#             md_pub.TbYearDvpunitOilstimResult.Stim_IncreOil_Average  # 平均增油量
#         ).filter(
#             md_pub.TbYearDvpunitOilstimResult.DvpUnit_Name == dvpUnit_Name,
#             md_pub.TbYearDvpunitOilstimResult.StimType_Name == stimType_Name,
#             md_pub.TbYearDvpunitOilstimResult.Year == year,
#         ).first()
#         project_inf['Stim_WellValidRatio'] = None
#         project_inf['Stim_WellNumber_Valid'] = None
#         project_inf['Stim_ValidPeriod_Average'] = None
#         project_inf['Stim_IncreOil_Average'] = None
#         if plan_proj:
#             data = dict(zip(plan_proj.keys(), plan_proj))
#             project_inf.update({'Stim_WellValidRatio': data['Stim_WellValidRatio']})
#             project_inf.update({'Stim_WellNumber_Valid': data['Stim_WellNumber_Valid']})
#             project_inf.update({'Stim_ValidPeriod_Average': data['Stim_ValidPeriod_Average']})
#             project_inf.update({'Stim_IncreOil_Average': data['Stim_IncreOil_Average']})
#         return project_inf
#
#     except Exception as e:
#         print('输入数据查找数据失败', e)
#         session_pub.rollback()
#         return False


# 根据条件查询税费明细
def query_ratio(well_name, start_year, end_year):
    try:
        dvp_name_db = session_pub.query(
            md_pub.TbWellbasic.Belong_DvpUnit_Name
        ).filter(
            md_pub.TbWellbasic.Well_Name.in_(well_name)
        ).all()
        dvpUnit_Name = []
        if dvp_name_db:
            for item in dvp_name_db:
                dvpUnit_Name.append(item[0])
        project_inf = session_pub.query(
            md_pub.TbYearDvpunitOilsalecostRatio).filter(
            md_pub.TbYearDvpunitOilsalecostRatio.DvpUnit_Name.in_(dvpUnit_Name),
            md_pub.TbYearDvpunitOilsalecostRatio.Year >= start_year,
            md_pub.TbYearDvpunitOilsalecostRatio.Year <= end_year
            ).order_by(
            md_pub.TbYearDvpunitOilsalecostRatio.DvpUnit_Name,
            md_pub.TbYearDvpunitOilsalecostRatio.Year
        ).all()
        result = [data.__dict__ for data in project_inf]
        return result
    except:
        print('输入数据查找数据失败')
        session_pub.rollback()
        return False


# 根据条件查询原油操作成本明细
def query_oil(well_name, start_year, end_year):
    try:
        dvp_name_db = session_pub.query(
            md_pub.TbWellbasic.Belong_DvpUnit_Name
        ).filter(
            md_pub.TbWellbasic.Well_Name.in_(well_name)
        ).all()
        dvpUnit_Name = []
        if dvp_name_db:
            for item in dvp_name_db:
                dvpUnit_Name.append(item[0])
        project_inf = session_pub.query(md_pub.TbYearDvpunitOilprodcost
                                        ) \
            .filter(md_pub.TbYearDvpunitOilprodcost.DvpUnit_Name.in_(dvpUnit_Name)
                    , md_pub.TbYearDvpunitOilprodcost.Year >= start_year,
                    md_pub.TbYearDvpunitOilprodcost.Year <= end_year
                    ).order_by(md_pub.TbYearDvpunitOilprodcost.DvpUnit_Name,
                               md_pub.TbYearDvpunitOilprodcost.Year).all()
        result = [data.__dict__ for data in project_inf]
        return result
    except:
        print('输入数据查找数据失败')
        session_pub.rollback()
        return False


# 根据单元名称获取所有输入界面信息,开发单元，类别名称，年份
def get_all_data(dvpUnit_Name, stimType_Name, start_year, end_year):
    try:
        temp_results = session_pub.query(
            md_pub.TbYearDvpunitOilstimResult.DvpUnit_Name,
            md_pub.TbYearDvpunitOilstimResult.StimType_Name,
            md_pub.TbYearDvpunitOilstimResult.Year
        ).filter(
            md_pub.TbYearDvpunitOilstimResult.DvpUnit_Name.in_(dvpUnit_Name),
            md_pub.TbYearDvpunitOilstimResult.Year <= end_year,
            md_pub.TbYearDvpunitOilstimResult.Year >= start_year,
            md_pub.TbYearDvpunitOilstimResult.StimType_Name.in_(stimType_Name)
        ).all()
        temp_result_dict = [dict(zip(result.keys(), result)) for result in temp_results]
        result_data = None
        if temp_result_dict:
            results = list()
            for result in temp_result_dict:
                temp_result = session_pub.query(
                    md_pub.TbYearDvpunitOilstimResult.DvpUnit_Name,
                    md_pub.TbYearDvpunitOilstimResult.Year,
                    md_pub.TbYearDvpunitOilstimResult.StimType_Name,
                    md_pub.TbYearDvpunitOilstimResult.Stim_WellNumber_Valid,  # 有效井次
                    md_pub.TbYearDvpunitOilstimResult.Stim_WellValidRatio,  # 有效率
                    md_pub.TbYearDvpunitOilstimResult.Stim_ValidPeriod_Average,  # 平均有有效期
                    md_pub.TbYearDvpunitOilstimResult.Stim_IncreOil_Average,  # 平均累计增油量

                    md_pub.TbYearDvpunitOilstimCost.Stim_Cost,  # 作业费用

                    md_pub.TbYearDvpunitOilprice.Oil_CommodityRatio,  # 原油商品率
                    md_pub.TbYearDvpunitOilprice.Oil_Price,  # 原油价格

                    md_pub.TbYearDvpunitDiscount.Money_Discount  # 资金贴现率
                ).filter(
                    md_pub.TbYearDvpunitOilstimResult.DvpUnit_Name == result['DvpUnit_Name'],
                    md_pub.TbYearDvpunitOilstimResult.Year == result['Year'],
                    md_pub.TbYearDvpunitOilstimResult.StimType_Name == result['StimType_Name'],

                    md_pub.TbYearDvpunitOilstimCost.DvpUnit_Name == result['DvpUnit_Name'],
                    md_pub.TbYearDvpunitOilstimCost.Year == result['Year'],
                    md_pub.TbYearDvpunitOilstimCost.StimType_Name == result['StimType_Name'],

                    md_pub.TbYearDvpunitOilprice.DvpUnit_Name == result['DvpUnit_Name'],
                    md_pub.TbYearDvpunitOilprice.Year == result['Year'],

                    md_pub.TbYearDvpunitDiscount.DvpUnit_Name == result['DvpUnit_Name'],
                    md_pub.TbYearDvpunitDiscount.Year == result['Year']
                ).first()
                if temp_result:
                    results.append(temp_result)
            result_data = [dict(zip(result.keys(), result)) for result in results]
        return result_data
    except Exception as e:
        print('输入数据查找数据失败', e)
        session_pub.rollback()
        return False


#   存库 原油销售税费率表
# hzc改
class year_dvpunit_oilsalecost_ratio():
    return_data = list()

    def updata(self, data):
        try:
            session_pub.query(md_pub.TbYearDvpunitOilsalecostRatio). \
                filter(
                md_pub.TbYearDvpunitOilsalecostRatio.DvpUnit_Name == data["DvpUnit_Name"],
                md_pub.TbYearDvpunitOilsalecostRatio.Year == data["Year"]).update(
                {
                    md_pub.TbYearDvpunitOilsalecostRatio.DvpUnit_Name: data["DvpUnit_Name"],
                    md_pub.TbYearDvpunitOilsalecostRatio.Year: data["Year"],
                    md_pub.TbYearDvpunitOilsalecostRatio.OilSale_TotalTaxRatio: data["OilSale_TotalTaxRatio"],
                    md_pub.TbYearDvpunitOilsalecostRatio.AddedValue_TaxRatio: data["AddedValue_TaxRatio"],
                    md_pub.TbYearDvpunitOilsalecostRatio.Resource_TaxRatio: data["Resource_TaxRatio"],
                    md_pub.TbYearDvpunitOilsalecostRatio.EduAdd_TaxRatio: data["EduAdd_TaxRatio"],
                    md_pub.TbYearDvpunitOilsalecostRatio.CityDvpAdd_TaxRate: data["CityDvpAdd_TaxRate"],
                    md_pub.TbYearDvpunitOilsalecostRatio.Income_TaxRate: data["Income_TaxRate"],
                    md_pub.TbYearDvpunitOilsalecostRatio.ManageCost_Ratio: data["ManageCost_Ratio"],
                    md_pub.TbYearDvpunitOilsalecostRatio.Remark: data["Remark"]
                }
            )
            session_pub.commit()
            print('更新输入数据成功')
            return True
        except:
            print('更新输入数据失败')
            session_pub.rollback()
            return False

    def delete(self, id):
        try:
            session_pub.query(md_pub.TbYearDvpunitOilsalecostRatio) \
                .filter(md_pub.TbYearDvpunitOilsalecostRatio.DvpUnit_Name == id["DvpUnit_Name"],
                        md_pub.TbYearDvpunitOilsalecostRatio.Year == id["Year"]).delete()
            session_pub.commit()
            print('删除数据成功')
            return True
        except:
            print('删除数据失败')
            session_pub.rollback()
            return False

    def add(self, data):
        new_data = md_pub.TbYearDvpunitOilsalecostRatio(
            DvpUnit_Name=data["DvpUnit_Name"],
            Year=data["Year"],
            OilSale_TotalTaxRatio=data["OilSale_TotalTaxRatio"],
            AddedValue_TaxRatio=data["AddedValue_TaxRatio"],
            Resource_TaxRatio=data["Resource_TaxRatio"],
            EduAdd_TaxRatio=data["EduAdd_TaxRatio"],
            CityDvpAdd_TaxRate=data["CityDvpAdd_TaxRate"],
            Income_TaxRate=data["Income_TaxRate"],
            ManageCost_Ratio=data["ManageCost_Ratio"],
            Remark=data["Remark"]
        )
        try:
            session_pub.add(new_data)
            session_pub.commit()
            print('存入数据成功')
            session_pub.close()
            return True
        except:
            print('存入数据失败')
            session_pub.rollback()
            return False


# hzc改
def oilsalecost_ratio(radio_data):
    return_data = list()
    for data in radio_data:
        try:
            is_existed = session_pub.query(md_pub.TbYearDvpunitOilsalecostRatio).filter(
                md_pub.TbYearDvpunitOilsalecostRatio.DvpUnit_Name == data['DvpUnit_Name'],
                md_pub.TbYearDvpunitOilsalecostRatio.Year == data['Year']
            ).count()
            if is_existed:
                session_pub.query(md_pub.TbYearDvpunitOilsalecostRatio).filter(
                    md_pub.TbYearDvpunitOilsalecostRatio.DvpUnit_Name == data["DvpUnit_Name"],
                    md_pub.TbYearDvpunitOilsalecostRatio.Year == data["Year"]).update(
                    {
                        md_pub.TbYearDvpunitOilsalecostRatio.OilSale_TotalTaxRatio: data["OilSale_TotalTaxRatio"],
                        md_pub.TbYearDvpunitOilsalecostRatio.AddedValue_TaxRatio: data["AddedValue_TaxRatio"],
                        md_pub.TbYearDvpunitOilsalecostRatio.Resource_TaxRatio: data["Resource_TaxRatio"],
                        md_pub.TbYearDvpunitOilsalecostRatio.EduAdd_TaxRatio: data["EduAdd_TaxRatio"],
                        md_pub.TbYearDvpunitOilsalecostRatio.CityDvpAdd_TaxRate: data["CityDvpAdd_TaxRate"],
                        md_pub.TbYearDvpunitOilsalecostRatio.Income_TaxRate: data["Income_TaxRate"],
                        md_pub.TbYearDvpunitOilsalecostRatio.ManageCost_Ratio: data["ManageCost_Ratio"],
                        md_pub.TbYearDvpunitOilsalecostRatio.Remark: data["Remark"]
                    }
                )
            else:
                add_data = md_pub.TbYearDvpunitOilsalecostRatio(
                    DvpUnit_Name=data["DvpUnit_Name"],
                    Year=data["Year"],
                    OilSale_TotalTaxRatio=data["OilSale_TotalTaxRatio"],
                    AddedValue_TaxRatio=data["AddedValue_TaxRatio"],
                    Resource_TaxRatio=data["Resource_TaxRatio"],
                    EduAdd_TaxRatio=data["EduAdd_TaxRatio"],
                    CityDvpAdd_TaxRate=data["CityDvpAdd_TaxRate"],
                    Income_TaxRate=data["Income_TaxRate"],
                    ManageCost_Ratio=data["ManageCost_Ratio"],
                    Remark=data["Remark"]
                )
                session_pub.add(add_data)
            session_pub.commit()
            return_data.append(
                {
                    'DvpUnit_Name': data['DvpUnit_Name'],
                    'Year': data['Year'],
                    'result': True
                }
            )

        except Exception as e:
            return_data.append(
                {
                    'DvpUnit_Name': data['DvpUnit_Name'],
                    'Year': data['Year'],
                    'result': False
                }
            )
            session_pub.rollback()
            print(e)
            print(e.__traceback__.tb_lineno)
    return return_data


#   存库 吨油操作成本明细
class year_dvpunit_oilprodcost():

    def updata(self, data):
        try:
            session_pub.query(md_pub.TbYearDvpunitOilprodcost). \
                filter(md_pub.TbYearDvpunitOilprodcost.DvpUnit_Name == data["DvpUnit_Name"],
                       md_pub.TbYearDvpunitOilprodcost.Year == data["Year"]).update(
                {
                    md_pub.TbYearDvpunitOilprodcost.DvpUnit_Name: data["DvpUnit_Name"],
                    md_pub.TbYearDvpunitOilprodcost.Year: data["Year"],
                    md_pub.TbYearDvpunitOilprodcost.Oil_OprCost: data["Oil_OprCost"],
                    md_pub.TbYearDvpunitOilprodcost.FuelCost: data["FuelCost"],
                    md_pub.TbYearDvpunitOilprodcost.Power_Cost: data["Power_Cost"],
                    md_pub.TbYearDvpunitOilprodcost.FluidDispose_Cost: data["FluidDispose_Cost"],
                    md_pub.TbYearDvpunitOilprodcost.OilDisplaceAgent_Cost: data["OilDisplaceAgent_Cost"],
                    md_pub.TbYearDvpunitOilprodcost.NGLRecovery_Cost: data["NGLRecovery_Cost"],
                    md_pub.TbYearDvpunitOilprodcost.Transp_Cost: data["Transp_Cost"],
                    md_pub.TbYearDvpunitOilprodcost.WellTest_Cost: data["WellTest_Cost"],
                    md_pub.TbYearDvpunitOilprodcost.Other_Cost: data["Other_Cost"],
                    md_pub.TbYearDvpunitOilprodcost.Depre_Cost: data["Depre_Cost"],
                    md_pub.TbYearDvpunitOilprodcost.Remark: data["Remark"]
                }
            )
            session_pub.commit()
            print('更新输入数据成功')
            return True
        except:
            print('更新输入数据失败')
            session_pub.rollback()
            return False

    def delete(self, id):
        try:
            session_pub.query(md_pub.TbYearDvpunitOilprodcost) \
                .filter(md_pub.TbYearDvpunitOilprodcost.DvpUnit_Name == id["DvpUnit_Name"],
                        md_pub.TbYearDvpunitOilprodcost.Year == id["Year"]).delete()
            session_pub.commit()
            print('删除数据成功')
            return True
        except:
            print('删除数据失败')
            session_pub.rollback()
            return False

    def add(self, data):
        new_data = md_pub.TbYearDvpunitOilprodcost(
            DvpUnit_Name=data["DvpUnit_Name"],
            Year=data["Year"],
            Oil_OprCost=data["Oil_OprCost"],
            FuelCost=data["FuelCost"],
            Power_Cost=data["Power_Cost"],
            FluidDispose_Cost=data["FluidDispose_Cost"],
            OilDisplaceAgent_Cost=data["OilDisplaceAgent_Cost"],
            NGLRecovery_Cost=data["NGLRecovery_Cost"],
            Transp_Cost=data["Transp_Cost"],
            WellTest_Cost=data["WellTest_Cost"],
            Other_Cost=data["Other_Cost"],
            Depre_Cost=data["Depre_Cost"],
            Remark=data["Remark"]
        )
        try:
            session_pub.add(new_data)
            session_pub.commit()
            print('存入数据成功')
            session_pub.close()
            return True
        except:
            print('存入数据失败')
            session_pub.rollback()
            return False


# hzc改
def oilprodcost(cost_data):
    return_data = list()
    for data in cost_data:
        try:
            is_existed = session_pub.query(md_pub.TbYearDvpunitOilprodcost).filter(
                md_pub.TbYearDvpunitOilprodcost.DvpUnit_Name == data['DvpUnit_Name'],
                md_pub.TbYearDvpunitOilprodcost.Year == data['Year']
            ).count()
            if is_existed:
                session_pub.query(md_pub.TbYearDvpunitOilprodcost). \
                    filter(md_pub.TbYearDvpunitOilprodcost.DvpUnit_Name == data["DvpUnit_Name"],
                           md_pub.TbYearDvpunitOilprodcost.Year == data["Year"]).update(
                    {
                        md_pub.TbYearDvpunitOilprodcost.Oil_OprCost: data["Oil_OprCost"],
                        md_pub.TbYearDvpunitOilprodcost.FuelCost: data["FuelCost"],
                        md_pub.TbYearDvpunitOilprodcost.Power_Cost: data["Power_Cost"],
                        md_pub.TbYearDvpunitOilprodcost.FluidDispose_Cost: data["FluidDispose_Cost"],
                        md_pub.TbYearDvpunitOilprodcost.OilDisplaceAgent_Cost: data["OilDisplaceAgent_Cost"],
                        md_pub.TbYearDvpunitOilprodcost.NGLRecovery_Cost: data["NGLRecovery_Cost"],
                        md_pub.TbYearDvpunitOilprodcost.Transp_Cost: data["Transp_Cost"],
                        md_pub.TbYearDvpunitOilprodcost.WellTest_Cost: data["WellTest_Cost"],
                        md_pub.TbYearDvpunitOilprodcost.Other_Cost: data["Other_Cost"],
                        md_pub.TbYearDvpunitOilprodcost.Depre_Cost: data["Depre_Cost"],
                        md_pub.TbYearDvpunitOilprodcost.Remark: data["Remark"]
                    }
                )
            else:
                add_data = md_pub.TbYearDvpunitOilprodcost(
                    DvpUnit_Name=data["DvpUnit_Name"],
                    Year=data["Year"],
                    Oil_OprCost=data["Oil_OprCost"],
                    FuelCost=data["FuelCost"],
                    Power_Cost=data["Power_Cost"],
                    FluidDispose_Cost=data["FluidDispose_Cost"],
                    OilDisplaceAgent_Cost=data["OilDisplaceAgent_Cost"],
                    NGLRecovery_Cost=data["NGLRecovery_Cost"],
                    Transp_Cost=data["Transp_Cost"],
                    WellTest_Cost=data["WellTest_Cost"],
                    Other_Cost=data["Other_Cost"],
                    Depre_Cost=data["Depre_Cost"],
                    Remark=data["Remark"]
                )
                session_pub.add(add_data)
            session_pub.commit()
            return_data.append(
                {
                    'DvpUnit_Name': data['DvpUnit_Name'],
                    'Year': data['Year'],
                    'result': True
                }
            )

        except Exception as e:
            return_data.append(
                {
                    'DvpUnit_Name': data['DvpUnit_Name'],
                    'Year': data['Year'],
                    'result': False
                }
            )
            session_pub.rollback()
            print(e)
            print(e.__traceback__.tb_lineno)
    return return_data

def deletefun(delete):
    result = list()
    for data in delete:
        try:
            db_data = session_pub.query(md_pub.TbOilwellstimResult).filter(
                md_pub.TbOilwellstimResult.Well_Name == data['Well_Name'],
                md_pub.TbOilwellstimResult.Stim_Date == data['Stim_Date'],
                md_pub.TbOilwellstimResult.StimType_Name == data['StimType_Name']
            )
            if db_data.first():
                db_data.delete()
                session_pub.commit()
                result.append({
                    'Well_Name': data['Well_Name'],
                    'Stim_Date': data['Stim_Date'],
                    'StimType_Name': data['StimType_Name'],
                    'result': True,
                    'message': '删除成功'
                })
            else:
                result.append({
                    'Well_Name': data['Well_Name'],
                    'Stim_Date': data['Stim_Date'],
                    'StimType_Name': data['StimType_Name'],
                    'result': False,
                    'message': '无此数据'
                })
        except Exception as e:
            print(e, e.__traceback__.tb_lineno)
            session_pub.rollback()
            result.append({
                'Well_Name': data['Well_Name'],
                'Stim_Date': data['Stim_Date'],
                'StimType_Name': data['StimType_Name'],
                'result': False,
                'message': '异常'
            })
    return result

# 存库更新部分数据
# def input_updata(input_upd):
#     try:
#         session_pro.query(md_pro.TbUserprojDvpunitOilstimevalInput). \
#             filter(md_pro.TbUserprojDvpunitOilstimevalInput.User_ID == input_upd["User_ID"],
#                    md_pro.TbUserprojDvpunitOilstimevalInput.Proj_ID == input_upd["Proj_ID"]).update(
#             {
#                 md_pro.TbUserprojDvpunitOilstimevalInput.DvpUnit_Name: input_upd["DvpUnit_Name"],
#                 md_pro.TbUserprojDvpunitOilstimevalInput.Year: input_upd["Year"],
#                 md_pro.TbUserprojDvpunitOilstimevalInput.StimType_Name: input_upd["StimType_Name"],
#                 md_pro.TbUserprojDvpunitOilstimevalInput.Stim_WellNumber_Valid: input_upd["Stim_WellNumber_Valid"],
#                 md_pro.TbUserprojDvpunitOilstimevalInput.Stim_WellValidRatio: input_upd["Stim_WellValidRatio"],
#                 md_pro.TbUserprojDvpunitOilstimevalInput.Stim_ValidPeriod_Average: input_upd[
#                     "Stim_ValidPeriod_Average"],
#                 md_pro.TbUserprojDvpunitOilstimevalInput.Stim_IncreOil_Average: input_upd["Stim_IncreOil_Average"],
#                 md_pro.TbUserprojDvpunitOilstimevalInput.StimCost_Average: input_upd["StimCost_Average"],
#                 md_pro.TbUserprojDvpunitOilstimevalInput.Oil_OprCost: input_upd["Oil_OprCost"],
#                 md_pro.TbUserprojDvpunitOilstimevalInput.Oil_Price: input_upd["Oil_Price"],
#                 md_pro.TbUserprojDvpunitOilstimevalInput.StimOil_CommodityRatio: input_upd["StimOil_CommodityRatio"],
#                 md_pro.TbUserprojDvpunitOilstimevalInput.OilSale_TotalTaxRatio: input_upd["OilSale_TotalTaxRatio"],
#                 md_pro.TbUserprojDvpunitOilstimevalInput.Money_Discount: input_upd["Money_Discount"],
#                 md_pro.TbUserprojDvpunitOilstimevalInput.Remark: input_upd["Remark"],
#             }
#         )
#         session_pro.commit()
#         print('更新输入数据成功')
#         return True
#     except:
#         print('更新输入数据失败')
#         return False


# 存库删除部分数据
def input_del(id):
    try:
        session_pro.query(md_pro.TbUserprojDvpunitOilstimevalInput) \
            .filter(md_pro.TbUserprojDvpunitOilstimevalInput.User_ID == id["User_ID"],
                    md_pro.TbUserprojDvpunitOilstimevalInput.Proj_ID == id["Proj_ID"]).delete()
        session_pro.commit()
        print('删除数据成功')
        return True
    except:
        print('删除数据失败')
        return False


# 将所有信息存库
"""
单元名称，年度，措施类别，有效井次，有效率，平均有效期，平均措施增油,
平均作业成本，操作吨油成本，平均油价，原油商品率，平均销售税费率，资金贴现率，备注
"""


def input_add(input_data):
    # hzc改
    return_data = list()
    for data in input_data:
        try:
            is_existed = session_pub.query(md_pub.TbYearDvpunitOilstimResult).filter(
                md_pub.TbYearDvpunitOilstimResult.DvpUnit_Name == data['DvpUnit_Name'],
                md_pub.TbYearDvpunitOilstimResult.Year == data['Year'],
                md_pub.TbYearDvpunitOilstimResult.StimType_Name == data['StimType_Name']
            ).count()
            if is_existed:
                session_pub.query(md_pub.TbYearDvpunitOilstimResult).filter(
                    md_pub.TbYearDvpunitOilstimResult.DvpUnit_Name == data['DvpUnit_Name'],
                    md_pub.TbYearDvpunitOilstimResult.Year == data['Year'],
                    md_pub.TbYearDvpunitOilstimResult.StimType_Name == data['StimType_Name']
                ).update({
                    md_pub.TbYearDvpunitOilstimResult.Stim_WellNumber_Valid: data['Stim_WellNumber_Valid'],
                    md_pub.TbYearDvpunitOilstimResult.Stim_WellValidRatio: data['Stim_WellValidRatio'],
                    md_pub.TbYearDvpunitOilstimResult.Stim_ValidPeriod_Average: data['Stim_ValidPeriod_Average'],
                    md_pub.TbYearDvpunitOilstimResult.Stim_IncreOil_Average: data['Stim_IncreOil_Average'],
                    md_pub.TbYearDvpunitOilstimResult.Remark: data['Remark']})
                session_pub.query(md_pub.TbYearDvpunitOilstimCost).filter(
                    md_pub.TbYearDvpunitOilstimCost.DvpUnit_Name == data['DvpUnit_Name'],
                    md_pub.TbYearDvpunitOilstimCost.Year == data['Year'],
                    md_pub.TbYearDvpunitOilstimCost.StimType_Name == data['StimType_Name']
                ).update({
                    md_pub.TbYearDvpunitOilstimCost.Stim_Cost: data['Stim_Cost'],
                    md_pub.TbYearDvpunitOilstimCost.Remark: data['Remark']
                })
                session_pub.query(md_pub.TbYearDvpunitOilprice).filter(
                    md_pub.TbYearDvpunitOilprice.DvpUnit_Name == data['DvpUnit_Name'],
                    md_pub.TbYearDvpunitOilprice.Year == data['Year'],
                ).update({
                    md_pub.TbYearDvpunitOilprice.Oil_CommodityRatio: data['Oil_CommodityRatio'],
                    md_pub.TbYearDvpunitOilprice.Oil_Price: data['Oil_Price'],
                    md_pub.TbYearDvpunitOilprice.Remark: data['Remark']
                })
                session_pub.query(md_pub.TbYearDvpunitDiscount).filter(
                    md_pub.TbYearDvpunitDiscount.DvpUnit_Name == data['DvpUnit_Name'],
                    md_pub.TbYearDvpunitDiscount.Year == data['Year'],
                ).update({
                    md_pub.TbYearDvpunitDiscount.Money_Discount: data['Money_Discount'],
                    md_pub.TbYearDvpunitDiscount.Remark: data['Remark']
                })
            else:
                add_result_data = md_pub.TbYearDvpunitOilstimResult(
                    DvpUnit_Name=data['DvpUnit_Name'],
                    Year=data['Year'],
                    StimType_Name=data['StimType_Name'],
                    Stim_WellNumber_Valid=data['Stim_WellNumber_Valid'],
                    Stim_WellValidRatio=data['Stim_WellValidRatio'],
                    Stim_ValidPeriod_Average=data['Stim_ValidPeriod_Average'],
                    Stim_IncreOil_Average=data['Stim_IncreOil_Average'],
                    Remark=data['Remark']
                )
                add_cost_data = md_pub.TbYearDvpunitOilstimCost(
                    DvpUnit_Name=data['DvpUnit_Name'],
                    Year=data['Year'],
                    StimType_Name=data['StimType_Name'],
                    Stim_Cost=data['Stim_Cost'],
                    Remark=data['Remark']
                )
                add_price_data = md_pub.TbYearDvpunitOilprice(
                    DvpUnit_Name=data['DvpUnit_Name'],
                    Year=data['Year'],
                    Oil_CommodityRatio=data['Oil_CommodityRatio'],
                    Oil_Price=data['Oil_Price'],
                    Remark=data['Remark']
                )
                add_discount_data = md_pub.TbYearDvpunitDiscount(
                    DvpUnit_Name=data['DvpUnit_Name'],
                    Year=data['Year'],
                    Money_Discount=data['Money_Discount'],
                    Remark=data['Remark']
                )
                session_pub.add(add_result_data)
                session_pub.add(add_cost_data)
                session_pub.add(add_price_data)
                session_pub.add(add_discount_data)

            session_pub.commit()
            return_data.append({
                'DvpUnit_Name': data['DvpUnit_Name'],
                'Year': data['Year'],
                'StimType_Name': data['StimType_Name'],
                'result': True
            })

        except Exception as e:
            return_data.append({
                'DvpUnit_Name': data['DvpUnit_Name'],
                'Year': data['Year'],
                'StimType_Name': data['StimType_Name'],
                'result': False,
            })
            session_pub.rollback()
            print(e)
            continue
    return return_data


# # 获取所有单元名称和措施类别，按年份排序
# def get_name_year():
#     try:
#         name = session_pro.query(md_pro.TbUserprojDvpunitOilstimevalInput.DvpUnit_Name  # 单元名称
#                                  , md_pro.TbUserprojDvpunitOilstimevalInput.Year  # 年度
#                                  , md_pro.TbUserprojDvpunitOilstimevalInput.StimType_Name  # 措施类别
#                                  ).order_by(md_pro.TbUserprojDvpunitOilstimevalInput.Year).all()
#         return name
#     except:
#         session_pro.rollback()
#         print("获取单元名称和类别失败")
#         return False


# 获取所有单元名称和措施类别，按年份排序
def get_name_year_public(planproj_name: str):
    try:
        unit_and_year = session_pub.query(
            md_pub.TbYearDvpunitOilstimPlanprojForecast.DvpUnit_Name,
            md_pub.TbYearDvpunitOilstimPlanprojForecast.Year
        ).filter(
            md_pub.TbYearDvpunitOilstimPlanprojForecast.DvpUnit_OilStim_PlanProj_Name == planproj_name
        ).distinct().all()
        if unit_and_year:
            units = [unit[0] for unit in unit_and_year]
            years = [year[1] for year in unit_and_year]
        else:
            units = None
            years = None
        stim_type = session_pub.query(
            md_pub.TbOilwellstimType.StimType_Name,
            md_pub.TbOilwellstimType.Belong_StimType_Name,
            md_pub.TbOilwellstimType.StimType_Rank,
            md_pub.TbOilwellstimType.StimType_ID
        ).all()
        stim_type = [dict(zip(type.keys(), type)) for type in stim_type]

        # 处理措施数据，生成树形结构
        stim_type_tree = list()
        for type in stim_type:
            temp_dic = dict()
            if type['StimType_Rank'] == '1':
                temp_dic['id'] = type['StimType_ID']
                temp_dic['title'] = type['StimType_Name']
                children = create_tree(stim_type, type['StimType_Name'], "措施")
                if children:
                    temp_dic['children'] = children
                stim_type_tree.append(temp_dic)

        response_data = {
            "DvpUnit": units,
            "Year": years,
            "StimType": stim_type_tree if stim_type_tree else None
        }

        return response_data
    except Exception as e:
        session_pub.rollback()
        print(e)
        return False


def create_tree(total_data, parent_unit_name, data_type):
    if data_type == "开发单元":
        belong_str, id_str, name_str = "Belong_DvpUnit_Name", "DvpUnit_ID", "DvpUnit_Name"
    elif data_type == "措施":
        belong_str, id_str, name_str = "Belong_StimType_Name", "StimType_ID", "StimType_Name"
    tree = []
    try:
        for data in total_data:
            if data_type == "措施" and data['StimType_Rank'] == "1":
                continue
            temp_dic = dict()
            if data[belong_str] == parent_unit_name:
                temp_dic['id'] = data[id_str]
                temp_dic['title'] = data[name_str]
                children = create_tree(total_data, data[name_str], data_type)
                if children:
                    temp_dic['children'] = children
                tree.append(temp_dic)
        return tree
    except Exception as e:
        print(e)


# BP神经网络预测 读取规划方案、单元名称、起止年度
def read_Plan_Unit_Year():
    try:
        DvpUnit_OilStim_PlanProj_Name = session_pub.query(
            md_pub.TbYearDvpunitOilstimPlanprojMessage.DvpUnit_OilStim_PlanProj_Name).all()

        units = session_pub.query(md_pub.TbDvpunitbaisc.DvpUnit_Name, md_pub.TbDvpunitbaisc.Belong_DvpUnit_Name,
                                  md_pub.TbDvpunitbaisc.DvpUnit_ID).all()
        units = [dict(zip(unit.keys(), unit)) for unit in units]

        StimPlanProj_StartYear = session_pub.query(
            md_pub.TbYearDvpunitOilstimPlanprojMessage.StimPlanProj_StartYear).filter().all()
        StimPlanProj_EndYear = session_pub.query(
            md_pub.TbYearDvpunitOilstimPlanprojMessage.StimPlanProj_EndYear).filter().all()
        planName = []
        unitName = create_tree(units, None, "开发单元")
        Year = []
        for i in range(len(DvpUnit_OilStim_PlanProj_Name)):
            planName.append(DvpUnit_OilStim_PlanProj_Name[i][0])

        for i in range(len(StimPlanProj_StartYear)):
            Year.append(int(StimPlanProj_StartYear[i][0]))
        for i in range(len(StimPlanProj_EndYear)):
            Year.append(int(StimPlanProj_EndYear[i][0]))
        minYear = Year[0]
        maxYear = Year[0]
        for i in range(len(Year)):
            if Year[i] < minYear:
                minYear = Year[i]
            if Year[i] > maxYear:
                maxYear = Year[i]
        return {
            "planName": planName if planName else None,
            "unitName": unitName if unitName else None,
            "yearRange": [minYear, maxYear]
        }
    except Exception as e:
        print(e)
        print(e.__traceback__.tb_lineno)
        return False


def get_projId_by_user_id(user_id):
    try:
        input_project_inf = session_pro.query(
            md_pro.TbUserprojWellInput.Proj_ID
        ).filter(
            md_pro.TbUserprojWellInput.User_ID == user_id
        ).all()

        out_project_inf = session_pro.query(
            md_pro.TbUserprojWellOut.Proj_ID
        ).filter(
            md_pro.TbUserprojWellOut.User_ID == user_id
        ).all()

        return input_project_inf, out_project_inf
    except Exception as e:
        print('查找数据失败', e)
        session_pro.rollback()
        return False


def read_pri_well(well_name, stimType_Name, start_year, end_year):
    try:
        dvp_name_db = session_pub.query(
            md_pub.TbWellbasic.Belong_DvpUnit_Name
        ).filter(
            md_pub.TbWellbasic.Well_Name.in_(well_name)
        ).all()
        dvpUnit_Name = []
        if dvp_name_db:
            for item in dvp_name_db:
                dvpUnit_Name.append(item[0])
        temp_results = session_pub.query(
            md_pub.TbYearDvpunitOilstimCost.DvpUnit_Name,
            md_pub.TbYearDvpunitOilstimCost.StimType_Name,
            md_pub.TbYearDvpunitOilstimCost.Year
        ).filter(
            md_pub.TbYearDvpunitOilstimCost.DvpUnit_Name.in_(dvpUnit_Name),
            md_pub.TbYearDvpunitOilstimCost.Year <= end_year[:4],
            md_pub.TbYearDvpunitOilstimCost.Year >= start_year[:4],
            md_pub.TbYearDvpunitOilstimCost.StimType_Name.in_(stimType_Name)
        ).all()
        temp_result_dict = [dict(zip(result.keys(), result)) for result in temp_results]
        result_data = None
        if temp_result_dict:
            results = list()
            for result in temp_result_dict:
                temp_result = session_pub.query(
                    md_pub.TbYearDvpunitOilstimCost.DvpUnit_Name,
                    md_pub.TbYearDvpunitOilstimCost.StimType_Name,
                    md_pub.TbYearDvpunitOilstimCost.Year,
                    md_pub.TbYearDvpunitOilstimCost.Remark,

                    md_pub.TbOilwellstimResult.Well_Name,  # 井号
                    md_pub.TbOilwellstimResult.Stim_Date,  # 措施日期
                    md_pub.TbOilwellstimResult.Stim_ValidPeriod,  # 有效期
                    md_pub.TbOilwellstimResult.Stim_IncreOil,  # 措施增油量

                    md_pub.TbYearDvpunitOilstimCost.Stim_Cost,  # 作业费用

                    md_pub.TbYearDvpunitOilprice.Oil_CommodityRatio,  # 原油商品率
                    md_pub.TbYearDvpunitOilprice.Oil_Price,  # 原油价格

                    md_pub.TbYearDvpunitOilprodcost.Oil_OprCost,  # 操作吨油成本

                    md_pub.TbYearDvpunitOilsalecostRatio.OilSale_TotalTaxRatio,  # 销售税费率

                    md_pub.TbYearDvpunitDiscount.Money_Discount  # 资金贴现率
                ).filter(

                    md_pub.TbOilwellstimResult.Well_Name.in_(well_name),
                    md_pub.TbOilwellstimResult.StimType_Name == result['StimType_Name'],
                    md_pub.TbOilwellstimResult.Stim_Date <= end_year,
                    md_pub.TbOilwellstimResult.Stim_Date >= start_year,

                    md_pub.TbYearDvpunitOilstimCost.DvpUnit_Name == result['DvpUnit_Name'],
                    md_pub.TbYearDvpunitOilstimCost.Year == result['Year'],
                    md_pub.TbYearDvpunitOilstimCost.StimType_Name == result['StimType_Name'],

                    md_pub.TbYearDvpunitOilprice.DvpUnit_Name == result['DvpUnit_Name'],
                    md_pub.TbYearDvpunitOilprice.Year == result['Year'],

                    md_pub.TbYearDvpunitOilprodcost.DvpUnit_Name == result['DvpUnit_Name'],
                    md_pub.TbYearDvpunitOilprodcost.Year == result['Year'],

                    md_pub.TbYearDvpunitOilsalecostRatio.DvpUnit_Name == result['DvpUnit_Name'],
                    md_pub.TbYearDvpunitOilsalecostRatio.Year == result['Year'],

                    md_pub.TbYearDvpunitDiscount.DvpUnit_Name == result['DvpUnit_Name'],
                    md_pub.TbYearDvpunitDiscount.Year == result['Year']
                ).first()
                if temp_result:
                    results.append(temp_result)
            result_data = [dict(zip(result.keys(), result)) for result in results]
        return result_data
    except Exception as e:
        print('输入数据查找数据失败', e)
        session_pub.rollback()
        return False
